﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lib.Web.Mvc.JQuery.JqGrid;
using ICDA.DataModel.Abstract;
using ICDA.DataModel.Concrete;
using ICDA.DataModel.Entity;
using System.Text;
using System.IO;
using ICDA.Web.Models;
using ICDA.Web.Helper;
using System.Collections;
using System.Net;

namespace ICDA.Web.Controllers
{
    public class HomeController : Controller
    {
        #region Fields
        IRepository _repository;
        LogOnModel loginModel = new LogOnModel();
        IEnumerable<ActivityTables> activity;
        private static UserModel _userModel;
        #endregion

        #region Constructors
        
        public static UserModel userModel
        {
            get
            {
                if (_userModel == null)
                {
                    _userModel = new UserModel();
                }
                return _userModel;
            }
        }
        public HomeController()
            : this(new DBrepository())
        {
        }

        public HomeController(IRepository repository)
        {
            _repository = repository;
        }

        #endregion

        #region Actions

        public ActionResult Index()
        {
            if (Session["UID"] != null)
            {
                ViewBag.Message = "Welcome to ICDA";
                return View();
            }
            else
            {
                return RedirectToAction("LogOn", "Account");
            }
        }

        public ActionResult About()
        {
            return View();
        }
        /// <summary>
        /// Activities this instance.
        /// </summary>
        /// <returns></returns>
        public ActionResult Activity()
        {
            if (Session["UID"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("LogOn", "Account");
            }
        }

        /// <summary>
        /// Activities the history.
        /// </summary>
        /// <returns></returns>
        public ActionResult ActivityHistory()
        {
            if (Session["UID"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("LogOn", "Account");
            }
        }

        /// <summary>
        /// Gets the task.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="viewModel">The view model.</param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetTask(JqGridRequest request, CustomSearchViewModel viewModel)
        {
            try
            {
                DatetTimeHelper dtHelper = new DatetTimeHelper();
                DateTime sdate = dtHelper.weekStartDate;
                DateTime edate = dtHelper.weekEndDate;
                string userID = Session["UID"].ToString().Trim();
                string UID = loginModel.UserName;
                if (userModel.Role == "Admin")
                {
                    activity = _repository.activity.Where(u => u.ActivityDate >= sdate && u.ActivityDate <= edate);
                }
                else
                {
                    activity = _repository.activity.Where(u => u.UserID == userID && u.ActivityDate >= sdate && u.ActivityDate <= edate);
                }
                int totalRecords = activity.Count();
                var data = activity;
                JqGridResponse response = new JqGridResponse()
                {
                    //Total pages count
                    TotalPagesCount = (int)Math.Ceiling((float)totalRecords / (float)request.RecordsCount),
                    //Page number
                    PageIndex = request.PageIndex,
                    //Total records count
                    TotalRecordsCount = totalRecords
                };
                //Table with rows data
                foreach (ActivityTables task in activity)
                {
                    response.Records.Add(new JqGridRecord(Convert.ToString(task.ID), new List<object>()
                {
                    task.ID,
                    task.Task,
                    task.ActivityDate,
                    task.TimeSpend,
                    task.OverTime,
                    task.UserID
                }));
                }

                //Return data as json
                return new JqGridJsonResult() { Data = response };
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }
        }

        /// <summary>
        /// Inserts the task.
        /// </summary>
        /// <param name="viewModel">The view model.</param>
        /// <returns></returns>
        public JsonResult InsertTask(ActivityViewModel viewModel)
        {
            try
            {
                string uid = Session["UID"].ToString().Trim();
                string userID = loginModel.UserName;
                var task = _repository.activity.Where(u => u.UserID == uid && u.ActivityDate == viewModel.ActivityDate).Sum(s => (int?)s.TimeSpend);
                task=task ?? 0;
                if (task + viewModel.TimeSpend < 10)
                {
                    ActivityTables act = new ActivityTables
                    {
                        ActivityDate = viewModel.ActivityDate,
                        OverTime = viewModel.OverTime,
                        Task = viewModel.Task,
                        UserID = uid,
                        TimeSpend = viewModel.TimeSpend
                    };
                    _repository.AddTask(act);
                    return Json(_repository.SaveChanges());
                }
                else
                {
                    ViewData["msg"] = "You can not add more than 9 hour task. Please add remaining Hours in overtime";
                    Response.StatusDescription = "You can not add more than 9 hour task.Please add remaining Hours in overtime";
                    return Json(Response);
                }
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return Json("Error Occured"); 
            }
        }
        /// <summary>
        /// Updates the task.
        /// </summary>
        /// <param name="viewModel">The view model.</param>
        /// <returns></returns>
        public ActionResult UpdateTask(ActivityViewModel viewModel)
        {
            try
            {
                string uid = Session["UID"].ToString().Trim();
                string userID = loginModel.UserName;
                ActivityTables act = _repository.activity.Where(u => u.ID == viewModel.ID).FirstOrDefault();
                act.ActivityDate = viewModel.ActivityDate;
                act.OverTime = viewModel.OverTime;
                act.Task = viewModel.Task;
                act.UserID = uid;
                act.TimeSpend = viewModel.TimeSpend;
                return Json(_repository.SaveChanges());
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }

        }

        /// <summary>
        /// Deletes the task.
        /// </summary>
        /// <param name="viewModel">The view model.</param>
        /// <returns></returns>
        public ActionResult DeleteTask(ActivityViewModel viewModel)
        {
            try
            {
                string uid = Session["UID"].ToString().Trim();
                int id = viewModel.ID;
                string userID = loginModel.UserName;
                ActivityTables act = _repository.activity.Where(u => u.ID == id).FirstOrDefault();
                _repository.DeleteTask(act);
                return Json(_repository.SaveChanges());
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }
        }

        /// <summary>
        /// Gets the historical records.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="viewModel">The view model.</param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetHistoricalRecords(JqGridRequest request, CustomSearchViewModel viewModel)
        {
            try
            {
                string userID = Session["UID"].ToString().Trim();
                string UID = loginModel.UserName;
                int totalRecords = 0;
                activity = _repository.activity.Where(u => u.UserID == userID);
                totalRecords = _repository.activity.Where(u => u.UserID == userID).Count();
                totalRecords = _repository.activity.Count();
                var data = _repository.activity.Where(u => u.UserID == userID);
                JqGridResponse response = new JqGridResponse()
                {
                    //Total pages count
                    TotalPagesCount = (int)Math.Ceiling((float)totalRecords / (float)request.RecordsCount),
                    //Page number
                    PageIndex = request.PageIndex,
                    //Total records count
                    TotalRecordsCount = totalRecords
                };
                //Table with rows data
                var acttable = _repository.activity.Join(_repository.users, u1 => u1.UserID, u2 => u2.UserID, (u1, u2) => new { Name = u2.Name, ID = u1.ID, UID = u1.UserID, Task = u1.Task, ActivityDate = u1.ActivityDate, TimeSpend = u1.TimeSpend, OverTime = u1.OverTime });
                foreach (var task in acttable)
                {
                    response.Records.Add(new JqGridRecord(Convert.ToString(task.ID), new List<object>()
                {
                    task.ID,
                    task.Name.Trim(),
                    task.Task,
                    task.ActivityDate,
                    task.TimeSpend,
                    task.OverTime,
                    task.UID
                }));
                }

                //Return data as json
                return new JqGridJsonResult() { Data = response };
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }
        }
        #endregion
    }
}
